package logic

import (
	"context"
	"errors"
	"gorm.io/gorm"
	"novel-kit/model/mysql"
	"strconv"
	"strings"

	"novel-kit/novelrpc/internal/svc"
	"novel-kit/novelrpc/novelrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CommentAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCommentAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CommentAddLogic {
	return &CommentAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 作品评论
func (l *CommentAddLogic) CommentAdd(in *novelrpc.CommentAddRequest) (*novelrpc.CommentAddResponse, error) {
	// todo: add your logic here and delete this line
	var findUser mysql.User
	if err := findUser.FindUserById(mysql.DB, in.UserId); err != nil {
		return nil, errors.New("该用户不存在")
	}
	var findNovel mysql.Novel

	if err := findNovel.FindNovelById(mysql.DB, in.NovelId); err != nil {
		return nil, errors.New("小说不存在")
	}

	if strings.Contains(in.Comment, "抄袭") || strings.Contains(in.Comment, "涉政") {
		return nil, errors.New("不允许有敏感词汇")
	}

	commentAdd := mysql.Comment{
		Model:   gorm.Model{},
		UserId:  int(in.UserId),
		NovelId: int(in.NovelId),
		Comment: in.Comment,
	}

	if err := commentAdd.CommentAdd(mysql.DB); err != nil {
		return nil, errors.New("添加失败")
	}
	return &novelrpc.CommentAddResponse{
		CommentId: strconv.Itoa(int(commentAdd.ID)),
	}, nil
}
